package com.cysyz.mylib.datacopytool.getterandsetteradapter;

import com.cysyz.mylib.datacopytool.GetterAndSetterType;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;

public class JavaBeanGetterAndSetterAdapter implements GetterAndSetterAdapter {

	@Override
	public boolean supports(Object obj) {
		return obj instanceof Object;
	}
	@Override
	public Object getValue(Object obj, String valueId) {
		try {
			PropertyDescriptor propertyDescriptor = new PropertyDescriptor(valueId, obj.getClass());
			return propertyDescriptor.getReadMethod().invoke(obj);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void setValue(Object obj, String valueId, Object val) {
		try {
			PropertyDescriptor propertyDescriptor = new PropertyDescriptor(valueId, obj.getClass());
			propertyDescriptor.getWriteMethod().invoke(obj, val);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}

	@Override
	public GetterAndSetterType getGetterAndSetterType() {
		return GetterAndSetterType.KEYWORD;
	}

	@Override
	public String[] getAllValueIds(Object obj) {
		Field[] declaredFields = obj.getClass().getDeclaredFields();
		String[] result = new String[declaredFields.length];
		for (int i = 0 ; i < declaredFields.length ; i++) {
			result[i] = declaredFields[i].getName();
		}
		return result;
	}

}
